package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.CollectCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.thread.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService service;

    @Resource
    WmNewsMaterialMapper mapper;

    static List<String> suffixList = new ArrayList<>();
    static {
        suffixList.add("jpg");
        suffixList.add("jpeg");
        suffixList.add("gif");
        suffixList.add("png");
    }

    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String website;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null||user.getId()==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = StringUtils.substringAfterLast(originalFilename, ".");
        if (!checkSuffix(suffix)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        String uuid = UUID.randomUUID().toString();
        String store = service.store(prefix, uuid+"."+suffix, inputStream);
        log.warn("store方法返回path为{}",store);
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setUserId(user.getId());
        wmMaterial.setUrl(store);
        save(wmMaterial);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private boolean checkSuffix(String suffix) {
        return suffixList.contains(suffix);

    }

    @Override
    public ResponseResult picList(WmMaterialDTO dto) {
//        参数检查
        if (dto == null || dto.getIsCollection() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
//        登录检查
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null || user.getId()==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
//        检查收藏
        if (dto.getIsCollection().intValue() == 1){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
//        筛选对应用户、排序、分页
        wrapper.eq(WmMaterial::getUserId,user.getId());
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmMaterial> iPage = page(page, wrapper);
        List<WmMaterial> records = iPage.getRecords();
//        修改url,增加前缀
        for (WmMaterial record : records) {
            record.setUrl(website+record.getUrl());
        }
//        log.warn(records.get(0).getUrl());
        return new PageResponseResult(dto.getPage(),dto.getSize(),iPage.getTotal(),records);
    }

    @Override
    public ResponseResult delPic(Integer id) {
        if (id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial one = getById(id);
        if (one == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer count = mapper.selectCount(new LambdaQueryWrapper<WmNewsMaterial>().eq(WmNewsMaterial::getMaterialId, one.getId()));
        if (count >0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"图片被引用，无法删除");
        }
        try {
            service.delete(one.getUrl());
        } catch (Exception e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"OSS删除出错");
        }
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateCollect(Integer id, CollectCodeEnum collectCodeEnum) {
        if (id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial one = getById(id);
        if (one == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (collectCodeEnum.getCode().intValue() == 0){
            one.setIsCollection((short)0);
            updateById(one);
        }else {
            one.setIsCollection((short)1);
            updateById(one);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
